import db from '~/DB';

import { getUser } from './user';
import { RestRequest } from 'msw';
import { Menu } from '~~/DB/types/menu.d';
import { Status } from '~~/DB/types/status.d';

interface T extends RestRequest {
  menus?: string[];
}

export async function getUserMenus(req: T) {
  const user = await getUser(req);
  if (!req.menus) {
    if (user) {
      const { roles } = user;

      if (roles.includes('admin')) {
        // const menus = await db.menus.where({ status: Status.enable }).toArray();
        req.menus = ['admin'];
      } else {
        const rolesData = await db.roles.where('key').anyOf(roles).toArray();
        const menuKeys = [...new Set(rolesData.flatMap((v) => v.menus))];
        const menus = await db.menus.where('key').anyOf(menuKeys).toArray();
        req.menus = menus.map((v) => v.key);
      }
    }
  }
  return req.menus;
}

export async function hasMenu(req: T, key: string) {
  // const user = await getUser(req);
  // const { roles } = user;
  const menus = await getUserMenus(req);

  const isAdmin = menus?.includes('admin');

  const t = key.replaceAll(/[^&|()]+/g, (s) => {
    return String(Boolean(isAdmin || menus?.includes(s)));
  });
  return !!eval(t);
}
